<template>
    <q-dialog ref="dialog" @hide="onDialogHide">
        <q-card class="relative-position">
            <q-card-section class=" row bg-green text-white">
                <div class="col-2 text-left">
                    <q-btn round flat icon="close" @click="onDialogHide"></q-btn>
                </div>
                <div class="text-h6 col-8 text-center">录音
                    <q-badge v-if="booRecording" color="red">
                        <q-icon round name="mic_none" color="white"/>
                    </q-badge>
                </div>
                <div class="col-2 text-right">
                    <q-btn :disable="time === 0 || time >60" @click="_uploadRecorder" flat round icon="send"></q-btn>
                </div>
            </q-card-section>
            <q-separator/>
            <q-card-actions class="audio-play" :v-if="!loading">
                <q-card style="width: 100%;height: 100%">
                    <q-linear-progress :value="playRadio" color="green"/>
                    <q-linear-progress :value="timeRadio" color="pink"/>
                    <q-card-section class="row items-center no-wrap">
                        <div>
                            <div class="text-weight-bold">{{title}}.wav
                                <q-badge v-if="booPlaying" transparent align="middle" color="green" outline>
                                    {{playTime}}s
                                </q-badge>
                                <q-popup-edit v-model="title" content-class="bg-white text-green">
                                    <q-input clearable color="green" v-model="title" maxlength="8"
                                             :rules="[
                                              val => !!val || '不能为空*',
                                              val => val.length < 8 || '最多不能超过8个字',
                                            ]"
                                             dense autofocus counter>
                                    </q-input>
                                </q-popup-edit>

                            </div>
                            <div class="text-grey">时长：{{time}} s</div>
                        </div>

                        <q-space/>

                        <q-btn :disable="booPlaying || booRecording || time === 0" flat round icon="replay" @click="_recorderReplay"/>
                        <q-btn :disable="booRecording || time === 0" flat round @click="_recorderPlay"
                               :icon=" booPlaying?'pause_circle_filled':'play_circle_outline'"/>
                    </q-card-section>

                </q-card>
            </q-card-actions>

            <q-card-actions class="audio-recorder" align="center" :v-if="!loading">
                <q-btn :disable="booPlaying" v-if="time<60" @click="_recorder" round
                       :icon=" booRecording?'pause_circle_filled':'mic_none'"
                       :color="booRecording?'red':'green'" :ripple="{
                  center: true }" size="lg"/>
                <div v-else class="text-red">录音最大为60s</div>
            </q-card-actions>
            <q-inner-loading dark :showing="loading">
                <q-spinner-comment size="50px" color="green"/>
            </q-inner-loading>
        </q-card>

    </q-dialog>

</template>

<script>
  import Recorder from 'js-audio-recorder'
  import BenderConfig from "../../sdk/config";
  import JIM from "../../utils/JIM";

  let recorder = new Recorder()
  let timer = null
  let playTimer = null
  export default {
    name: "index",
    data () {
      return {
        filePath: BenderConfig.uploadPath,
        title: '录音文件',
        loading: false,
        booRecording: false,
        booPlaying: false,
        time: 0,
        maxTime: 60,
        timeRadio: 0,
        playTime: 0,
        playMaxTime: 0,
        playRadio: 0
      }
    },
    watch: {
      time: function (value) {
        this.timeRadio = value / this.maxTime
        this.playMaxTime = value
      },
      playTime: function (value) {
        this.playRadio = value / this.playMaxTime
      }
    },
    methods: {
      // 以下方法是必需的
      // (不要改变它的名称 --> "show")
      show () {
        this.$refs.dialog.show()
      },
      /**
       * 销毁录音实例
       */
      hide () {//
        this._recorderReplay()
        this.$refs.dialog.hide()
      },
      _recorderReplay () {
        recorder.destroy(function () {
          recorder = null
        })
        this.time = 0
        this.playTime = 0
        this._clearTimer()
        this.booRecording = false
        this.booPlaying = false
      },
      _clearTimer () {
        if (timer) {
          clearInterval(timer);
          timer = null
        }
      },
      onDialogHide () {
        // QDialog发出“hide”事件时
        // 需要发出
        this.hide()
      },
      _onProcess () {
        const that_ = this
        timer = setInterval(function () {
          that_.time = that_.time + 1
          if (that_.time === 60) {
            that_._recorderStop()
          }
        }, 1000)
      },
      _recorder () {
        if (!recorder) {
          recorder = new Recorder()
        }
        if (this.booRecording) {
          this._recorderStop()
        } else {
          if (this.time === 0) {
            this._recorderStart()
          } else {
            this._recorderResume()
          }
        }
      },
      _recorderStart () {
        this.booRecording = true
        recorder.start()// 开始录音
        this._onProcess()
      },
      _recorderResume () {
        this.booRecording = true
        recorder.resume()// 继续录音
        this._onProcess()
      },
      _recorderStop () {
        recorder.stop() // 结束录音
        this.booRecording = false
        this._clearTimer()

      },
      _recorderPlay () {
        if (this.booPlaying) {
          this.booPlaying = false
          recorder.stopPlay() // 录音播放
          this.playTime = 0
          if (playTimer) {
            clearInterval(playTimer);
            playTimer = null
          }
        } else {
          this.booPlaying = true
          recorder.play() // 录音播放
          this._playProcess()
        }
      },
      _playProcess () {
        const that_ = this
        playTimer = setInterval(function () {
          that_.playTime = that_.playTime + 1
          if (that_.playTime === that_.playMaxTime) {
            that_._recorderPlay()
          }
        }, 1000)
      },
      _uploadRecorder () {
        try {
          this.loading = true
          if (recorder && this.time > 0) {
            let upload = recorder.getWAVBlob()
            const that_ = this
            if (upload) {
              let formData = new FormData()
              formData.append('file', upload, that_.title + '.wav')
              formData.append('timeSize', that_.time + '')
              const xhr = new XMLHttpRequest()
              xhr.open('POST', that_.filePath, true)  //server url自行填充，true代表异步
              xhr.send(formData)
              xhr.onload = () => {
                let res = JSON.parse(xhr.response)
                if (res.status === 200) {
                  let data = res.data[0]
                  let content = {
                    url: data.url,
                    fileName: data.fileName,
                  }
                  const j_im_send_req = {
                    chatType: 1,
                    cmd: 11,
                    content: JSON.stringify(content),
                    createTime: new Date().getMilliseconds(),
                    from: localStorage.getItem('imUserName'),
                    group_id: localStorage.getItem('chatGroupId'),
                    msgType: 2
                  }
                  JIM.send(JSON.stringify(j_im_send_req))
                  that_.onDialogHide()
                }
              }
            }
          }
        } catch (e) {
          this.loading = false
        }

      },
      _recorderDownload () {
        recorder.downloadWAV()
      }
    }
  }
</script>

<style scoped>
    .audio-play {
        height: 90px;
        width: 300px;
    }

    .audio-recorder {
        height: 100px;
        width: 300px;
    }
</style>
